//
//  VGIMTeamListViewController.swift
//  IMTest
//
//  Created by 宋海胜 on 2019/4/24.
//  Copyright © 2019年 宋海胜. All rights reserved.
//

import UIKit

class VGIMTeamListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    fileprivate var memberList: Array<NIMTeamMember>?
    fileprivate var teamId: String?
    
    fileprivate lazy var tableView: UITableView = {
        let view: UITableView = UITableView(frame: CGRect(x: 0, y: NAV_HEIGHT, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height - NAV_HEIGHT), style: .grouped)
        view.delegate = self
        view.dataSource = self
        view.separatorStyle = .none
        view.bounces = false
        view.backgroundColor = Constant.bgViewColor
        return view
    }()
    
    @objc init(_ teamId: String) {
        super.init(nibName: nil, bundle: nil)
        self.teamId = teamId
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = .white
        self.view.addSubview(self.tableView)
        self.requestData()
    }
    
    fileprivate func setupNav() {
        
//        addTopNavView(bgcolor: .white, leftimg: "back_black", lefttext: nil, leftTextColor: nil, title: "群成员(\(memberList?.count ?? 1))", titleTextColor: UIConstants.color_101, rightimg: nil, righttitle: nil, rightTextColor: nil)
//        addlineView(offset: 43.5 + UIConstants.STATUSBAR_HEIGHT)
    }
    
    fileprivate func requestData() {

        NIMSDK.shared().teamManager.fetchTeamMembers(self.teamId!) { [weak self] (error, members) in
            if (error == nil) {
                if let weakSelf = self {
                    for (_, value) in (members?.enumerated())! {
                        if value.userId == NIMSDK.shared().loginManager.currentAccount() {
                            
                        }
                    }
                    weakSelf.sortData(members: members)
                } else if (error! as NSError).code == NIMRemoteErrorCode.codeTeamNotMember.rawValue {
                    print("你已经不在群里")
                } else {
                    print("拉好友失败")
                }
            }
        }
    }
    
    fileprivate func sortData(members: Array<NIMTeamMember>?) {
        
        var membersCopy: Array<NIMTeamMember> = Array<NIMTeamMember>()
        if let arr = members {
            for (_, value) in arr.enumerated() {
                if value.type == .owner {
                    if membersCopy.count > 0 {
                        membersCopy.insert(value, at: 0)
                    } else {
                        membersCopy.append(value)
                    }
                } else if value.type == .manager {
                    membersCopy.append(value)
                }
            }
            for (_, value) in arr.enumerated() {
                if value.type == .normal || value.type == .apply {
                    membersCopy.append(value)
                }
            }
            self.memberList = membersCopy
            self.tableView.reloadData()
            self.setupNav()
        }
    }
    

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.memberList?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell: VGIMTeamListCell? = tableView.dequeueReusableCell(withIdentifier: "VGIMTeamListCell") as? VGIMTeamListCell
        if cell == nil {
            cell = VGIMTeamListCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: "VGIMTeamListCell")
        }
        cell?.configCell(model: self.memberList![indexPath.row])
        if indexPath.row == self.memberList?.count {
            cell?.hideLineView(hidden: true)
        } else {
            cell?.hideLineView(hidden: false)
        }
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        print("\(indexPath.row)")
//        if let userId = self.memberList![indexPath.row].userId, UserRepository.instance.getuser!.yxYqxImUserInfo.accid != userId {
//
//            let session: NIMSession = NIMSession(self.memberList![indexPath.row].userId!, type: .P2P)
//            let vc: VGIMOCSessionViewController = VGIMOCSessionViewController(session: session) {
//            }
//
//            self.navigationController?.pushViewController(vc, animated: true)
//        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view: UIView = UIView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 10))
        view.backgroundColor = Constant.bgViewColor
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view: UIView = UIView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 0.01))
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
}


class VGIMTeamListCell: UITableViewCell {
    
    
    fileprivate var avatar: UIImageView = {
        let img: UIImageView = UIImageView()
        img.layer.cornerRadius = 2
        img.layer.masksToBounds = true
        return img
    }()
    
    fileprivate var roleImage: UIImageView = {
        let img: UIImageView = UIImageView()
        return img
    }()
    
    fileprivate var nickNameLb: UILabel = {
        let lb: UILabel = UILabel()
        lb.text = "火星人～"
        lb.textColor = .black
        lb.font = UIFont.systemFont(ofSize: 15)
        return lb
    }()
    
    fileprivate var relationView: VGImgAndTextView = {
        let view: VGImgAndTextView = VGImgAndTextView()
        return view
    }()
    
    fileprivate lazy var locationView: VGImgAndTextView = {
        let view: VGImgAndTextView = VGImgAndTextView()
        return view
    }()
    
    fileprivate var lineView: UIView = {
        let view: UIView = UIView()
        view.backgroundColor = Constant.lineColor
        return view
    }()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        initViews()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    public func configCell(model: NIMTeamMember) {

        let userInfo = NIMKit.shared()?.info(byUser: model.userId, option: nil)
        if let urlStr = userInfo?.avatarUrlString {
            let url = URL(string: urlStr)
//            self.avatar.sd_setImage(with: url, placeholderImage: userInfo?.avatarImage, options: SDWebImageOptions.cacheMemoryOnly, completed: nil)
        }
        
        if model.teamId != nil {
//            let session: NIMSession = NIMSession(model.teamId!, type: .team)
//            if UserRepository.instance.getuser!.yxYqxImUserInfo.accid == model.userId {
//                self.nickNameLb.text = "我"
//            } else {
//                self.nickNameLb.text = NIMKitUtil.showNick(model.userId, in: session)
//            }
        }
        
        switch model.type {
        case NIMTeamMemberType.owner:
            self.roleImage.image = UIImage(named: "vgim_icon_team_creator")
        case NIMTeamMemberType.manager:
            self.roleImage.image = UIImage(named: "vgim_icon_team_manager")
        default:
            self.roleImage.image = nil
        }
//        self.relationView.configView(img: "", text: "")
//        self.locationView.configView(img: "", text: "")
    }
    
    fileprivate func initViews() {
        
        self.addSubview(self.avatar)
        self.addSubview(self.nickNameLb)
        self.addSubview(self.relationView)
        self.addSubview(self.locationView)
        self.avatar.addSubview(self.roleImage)
        self.addSubview(self.lineView)
        
        avatar.frame = CGRect(x: 12, y: 10, width: 40, height: 40)
        nickNameLb.frame = CGRect(x: 62, y: 20, width: self.frame.size.width - 62, height: 20)
        relationView.frame = CGRect(x: 82, y: 10 + 20, width: self.frame.size.width - 82, height: 20)
        locationView.frame = CGRect(x: 82, y: 10 + 40, width: self.frame.size.width - 82, height: 20)
        roleImage.frame = CGRect(x: 25, y: 25, width: 15, height: 15)
        lineView.frame = CGRect(x: 12, y: 60 - LINE_HEIGHT, width: SCREEN_WIDTH - 12, height: LINE_HEIGHT)
    }
    
    public func hideLineView(hidden: Bool) {
        lineView.isHidden = hidden
    }
}


class VGImgAndTextView: UIView {
    
    
    fileprivate var img: UIImageView = {
        let img: UIImageView = UIImageView()
        return img
    }()
    
    fileprivate var contentLb: UILabel = {
        let lb: UILabel = UILabel()
        lb.text = "来自火星～"
        lb.textColor = .gray
        lb.font = UIFont.systemFont(ofSize: 13)
        return lb
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        initViews()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    public func configView(img: String, text: String) {
        self.img.image = UIImage(named: img)
        self.contentLb.text = text
    }
    
    fileprivate func initViews() {
        self.addSubview(self.img)
        self.addSubview(self.contentLb)
        
        img.frame = CGRect(x: 0, y: 0, width: self.frame.size.height, height: self.frame.size.height)
        contentLb.frame = CGRect(x: 20, y: 0, width: self.frame.size.width - 20, height: self.frame.size.height)
    }
    
}
